<?php
class AdminTtfController extends Zend_Controller_Action
{
	public function preDispatch()
	{
		$url = $this->getRequest()->getRequestUri();
		$this->_helper->layout->setLayout('admin');
		if (!Zend_Auth::getInstance()->hasIdentity()) {
			$session = new Zend_Session_Namespace('ttf.auth');
			$session->requestURL = $url;
			$this->_redirect('/admin/login');
		}
	}
	
	public function indexAction()
	{
		
	}
	
	public function successAction()
	{
		if ($this->_helper->getHelper('FlashMessenger')->getMessages()) {
			$this->view->messages = $this->_helper->getHelper('FlashMessenger')->getMessages();
		} else {
			$this->_redirect('/admin/login');
		}
	}
	
	// Manager intro
	public function introAction()
	{
		$form = new TTF_Form_Intro();
		$this->view->form = $form;		
		if ($this->getRequest()->isPost()) {
			$postData = $this->getRequest()->getPost();
			if ($form->isValid($postData)) {
				$values = $form->getValues();
				$item = Doctrine::getTable('TTF_Model_Company')->find($values['id']);
				$item->fromArray($values);
				$item->save();
				$this->_redirect('/admin/gioi-thieu');
			}
		} else {
			$q = Doctrine_Query::create()
					->from('TTF_Model_Company c');
			$result = $q->fetchArray();
			$this->view->form->populate($result[0]);	
		}					
	}
	
	public function categoryAction()
	{
		$content_root = '';
		$q = Doctrine_Query::create()
				->from('TTF_Model_Categories c')
				->where('c.parent_id = 0');
		$results = $q->fetchArray();
		foreach ($results as $root) {
			list($content) = $this->get_children_of_category($root['id']);
			$content_root .= "<li><a href='#' >" . $root['name'] . "</a>";
			$content_root .= $content;
			$content_root .= "</li>\n";
		}	
		$this->view->categories = $content_root;	
	}
	
	public function get_children_of_category($category_id)
	{
		if (!isset($content)) {
			$content = '';
		}
		
		$q = Doctrine_Query::create()
				->from('TTF_Model_Categories c')
				->where('c.parent_id = ?', $category_id);
				
		$results = $q->fetchArray();
		if (count($results) > 0) {
			foreach ($results as $child) {
				list($content2) = $this->get_children_of_category($child['id']);
				$content .= "<li><a href='#' >" . $child['name'] . "</a>";
				$content .= $content2;
				$content .= "</li>\n";
			}
			$content = "<ul>" . $content . "</ul>";
		}
		return array($content);
	}
	
	public function productAction()
	{
		$q = Doctrine_Query::create()
			->from('TTF_Model_Foods f')
			->leftJoin('f.TTF_Model_Categories c')
			->leftJoin('f.TTF_Model_Currency r')
			->leftJoin('f.TTF_Model_Unit i');
		$result = $q->fetchArray();
		$this->view->foods = $result;
	}
	
	public function createAction()
	{
		$form = new TTF_Form_Food();
		$this->view->form = $form;
	}
}